﻿using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using db = XRM.Security.DataAccess.Models;

namespace XRM.Security.WebUI.Models.Department
{
    public class DepartmentModel : BaseViewModel,  IValidatableObject
    {
        public DepartmentModel()
        {
            AddressesList = new List<DepartmentAddressModel>();
        }

        public DepartmentModel(db.Department dbEntity)
        {
            AddressesList = new List<DepartmentAddressModel>();

            if (dbEntity != null)
            {
                Id = dbEntity.DepartmentId;
                Name = dbEntity.Name;

                if (dbEntity.DepartmentAddresses != null && dbEntity.DepartmentAddresses.Any())
                {
                    List<db.DepartmentAddress> list = dbEntity.DepartmentAddresses.OrderBy(x => x.Address).ToList();
                    foreach (db.DepartmentAddress address in list)
                    {
                        DepartmentAddressModel addressModel = new DepartmentAddressModel(address);
                        AddressesList.Add(addressModel);
                    }
                } 
            }
        }

        [AllowHtml]
        [Display(Name = "Наименование")]
        [Required(ErrorMessage = "Поле 'Наименование' обязательное")]
        [MaxLength(100, ErrorMessage = "Максимальная длина поля 'Наименование' 100 символов")]
        public string Name { get; set; }

        public string AddressColumnData
        {
            get
            {
                if (AddressesList.Any())
                    return AddressesList.Select(i => i.Address).ToList().Aggregate((current, next) => current + "<br/>" + next);
                else
                    return "";
            }
        }

        [AllowHtml]
        [Display( Name = "Адрес" )]
        public List<DepartmentAddressModel> AddressesList { get; set; }

        public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
        {
            AddressesList = AddressesList.Where(x => (!string.IsNullOrWhiteSpace(x.Address)) || (!x.CanDelete)).ToList();

            if (!AddressesList.Any())
            {
                yield return new ValidationResult("Поле 'Адрес' обязательное");
            }

            if (AddressesList.Where(x => string.IsNullOrWhiteSpace(x.Address)).Any())
            {
                yield return new ValidationResult("Поле 'Адрес' не может быть пустым");
            }

            if (AddressesList.Select(x => x.Address).Distinct().Count() != AddressesList.Count())
            {
                yield return new ValidationResult("Адреса подразделений не уникальны");
            }

            yield break;
        }
    }
}